package DesignPattern.Builder.FactoryPattern.ConfigFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

public class CoffeeFactory {
    /*
        加载配置文件，获取全类名，创建该类对象进行存储
        1.定义容器对象并存储
        2.调用load进行配置文件加载
     */
    private static HashMap<String, Coffee> coffeeHashMap = new HashMap<>();

    static {
        Properties p = new Properties();
        InputStream is = CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.properties");
        try {
            p.load(is);
            Set<Object> keys = p.keySet();
            for (Object key : keys) {
                String className = p.getProperty((String) key);
                // 通过反射创建对象
                Class clazz = Class.forName(className);
                Coffee coffee = (Coffee) clazz.newInstance();
                coffeeHashMap.put((String) key, coffee);
            }
            //
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 根据名称获取对象
    public static Coffee createCoffee(String name) {
        return coffeeHashMap.get(name);
    }
}
